//
//  DestinationTableViewController.m
//  We_Travel
//
//  Created by lanou3g on 15/12/11.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "DestinationTableViewController.h"
#import "Destination.h"
#import "DestinationCell.h"
#import "EditingViewController.h"
#import "url.h"
#import "CoreDataToolHelper.h"
#import "DestinationManager.h"
#import "SiteManager.h"

@interface DestinationTableViewController ()
@property (nonatomic , assign) BOOL flag;
@property (nonatomic , strong) UIWindow *window;
@property (nonatomic , strong) UIButton *completeBtn;
@property (nonatomic , strong) UIActivityIndicatorView *aiv;

@property (nonatomic,strong) NSMutableArray *dataArray;
@end

@implementation DestinationTableViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigation];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
    [self.tableView registerNib:[UINib nibWithNibName:@"DestinationCell" bundle:nil] forCellReuseIdentifier:@"destination"];
    self.aiv = [[UIActivityIndicatorView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.aiv];
    [self.aiv setColor:[UIColor redColor]];
    self.aiv.center = self.view.center;
    [self.aiv setHidesWhenStopped:YES];
    [self.aiv startAnimating];
    [self loadData];
}
//设置navigation
- (void)setupNavigation{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationController.navigationBar.barTintColor = [UIColor cyanColor];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"目的地";
}
- (void)leftBarButtonItemAction:(UIBarButtonItem *)sender{
  
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
     [self addView];
    [self.tableView reloadData];
}
- (void)addView
{
    self.completeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.completeBtn.frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
    self.completeBtn.backgroundColor = [UIColor redColor];
    [self.completeBtn setTitle:@"生成行程" forState:UIControlStateNormal];
    [self.completeBtn addTarget:self action:@selector(completeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds) - 40, self.view.frame.size.width, 40)];
    [self.window setWindowLevel:UIWindowLevelAlert];
    [self.window makeKeyAndVisible];
    [self.window addSubview:self.completeBtn];

}
//点击完成按钮
- (void)completeBtnAction:(UIButton *)sender
{
       if ([DestinationManager shareDestinationManager].SelectedDesArray.count<= 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"小提示：" message:@"请先选择目的地" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
    [SiteManager shareSiteManager].isNewPushCom = YES;
        //存入数据库
        [self saveCoreData];
    EditingViewController *editControl = [EditingViewController new];
    [self.navigationController pushViewController:editControl animated:YES];
  }
}
- (void)saveCoreData{
    [[CoreDataToolHelper shareCoreDataTool]addTravelCountryName:self.countryName CountryID:self.id_last];
    for (Destination *de in [DestinationManager shareDestinationManager].SelectedDesArray) {
    [[CoreDataToolHelper shareCoreDataTool]addTravelAreaName:de.name AreaID:de.ID areaDay:3 CountryCount:[[CoreDataToolHelper shareCoreDataTool]fetchCountry].count-1];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.window resignKeyWindow];
    self.window = nil;
}
- (void)loadData
{  [[DestinationManager shareDestinationManager]setResultBlock:^{
    [self.tableView reloadData];
    [self.aiv stopAnimating];
}];
    [[DestinationManager shareDestinationManager]requireData:HT_DestinationUrl idlast:self.id_last];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [DestinationManager shareDestinationManager].destinationArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DestinationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"destination" forIndexPath:indexPath];
    Destination *des = [DestinationManager shareDestinationManager].destinationArray[indexPath.row];
    cell.destination = des;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Destination *des = [DestinationManager shareDestinationManager].destinationArray[indexPath.row];
    if (des.isSelected == YES) {
        des.isSelected = NO;
       [[DestinationManager shareDestinationManager].SelectedDesArray removeObject:des];
    }else{
        des.isSelected = YES;
       [[DestinationManager shareDestinationManager].SelectedDesArray addObject:des];
    }
    [self.tableView reloadData];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(15, 15, 20,20)];
    imageview.image = [UIImage imageNamed:@"mulu.jpg"];
    [view addSubview:imageview];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 10, 200, 30)];
    label.textColor = [UIColor cyanColor];
    label.text = @"选目的地（可多选）";
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
